package com.db.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class WorkerThread implements Runnable {

	private Socket clientSocket;
	private Worker worker = new Worker();
	
    public WorkerThread(Socket clientSocket) {
		this.clientSocket = clientSocket;
	}

	public static void startPool(int suggestedPort) throws IOException {
        Parameter.setPort(suggestedPort);
        Parameter.print();
        int port = Parameter.getPort();
        int workers = Parameter.getWorkers();
        int timeout = Parameter.getTimeout(); 
        
        // create pool of worker threads
        ExecutorService pool = Executors.newFixedThreadPool(workers);
        
        // create server socket
        final ServerSocket serverSocket = new ServerSocket(port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override public void run() {
				try {
					serverSocket.close();
				} catch (IOException ignore) {}
			}
        });
        
        // accept connections
        while (true) {
        	Socket clientSocket = serverSocket.accept();
        	clientSocket.setSoTimeout(timeout);
        	pool.execute(new WorkerThread(clientSocket));
        }
    }

    public void run() {
    	try {
			worker.handleRequest(clientSocket);
		} catch (IOException e) {
			System.out.printf("%s(%d): %s%n",
					clientSocket.getInetAddress().getHostAddress(),
					clientSocket.getPort(),
					e.getMessage());
			try {
				clientSocket.close();
			} catch (IOException ignore) {}
		}
    }
}